package com.datatools.ui.sqledit;

import com.datatools.entity.ConnectionInfoEntity;
import com.datatools.i18n.BaseTextResource;
import com.datatools.ui.frame.LeftPanel;
import com.datatools.ui.frame.LeftPanelTreeNode;
import com.datatools.util.StringUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.Serializable;
import java.sql.*;
import java.util.List;
import java.util.Vector;

/**
 * SQL 编辑器ToolBar
 */
public class SQLEditToolBar extends JPanel implements Serializable {
    private static final long serialVersionUID = 1L;

    private BaseTextResource baseTextResource = BaseTextResource.getInstance();
    //所有连接节点
    private List<LeftPanelTreeNode> allLevel1ConnectionInfoNodes;
    //当前选择的连接节点
    private LeftPanelTreeNode currentSelectedConnectionInfoNode;
    //当前选择的连接信息实体
    private ConnectionInfoEntity currentSelectedConnectionInfoEntity;
    private Connection currentSelectedConnection;

    private SQLEditPanel sqlEditPanel ;

    //连接选择下拉
    private JComboBox connectionCombobox = new JComboBox();
    //数据库选择下拉
    private JComboBox databaseCombobox = new JComboBox();

    //选择执行
    private JButton selectedExecBtn = new JButton(baseTextResource.getSelectedExec());

    public void buildGUI() {
        this.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
        //添加边框
        //Border border = BorderFactory.createLineBorder(Color.red);
        //this.setBorder(border);
        //添加执行按钮
        this.add(selectedExecBtn);

        //添加连接下拉框、数据库下拉框
        connectionCombobox.setSize(200, 20);
        databaseCombobox.setSize(200, 20);
        this.add(connectionCombobox);
        this.add(databaseCombobox);

        //选择执行按钮 事件
        selectedExecBtn.addActionListener(new ActionListener() {
            public DefaultTableModel readResultSet(ResultSet rs) throws SQLException {
                DefaultTableModel tableModel = null;
                ResultSetMetaData rsMeta = null;
                while (rs.next()) {
                    if (null == tableModel) {
                        tableModel = new DefaultTableModel();
                    }
                    if (null == rsMeta) {
                        rsMeta = rs.getMetaData();
                        for (int i = 0; i < rsMeta.getColumnCount(); i++) {
                            //当前列名
                            String columnLabel = rsMeta.getColumnLabel(i + 1);
                            tableModel.addColumn(columnLabel);
                        }
                    }
                    Vector row = new Vector();
                    for (int i = 0; i < rsMeta.getColumnCount(); i++) {
                        //当前列名
                        String columnLabel = rsMeta.getColumnLabel(i + 1);
                        // 当前列的value
                        Object columnValue = rs.getObject(columnLabel);
                        row.add(columnValue);
                    }
                    tableModel.addRow(row);
                }
                return tableModel;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    //判断是否有选中SQL
                    String selectedSQLText = sqlEditPanel.getSqlEdit().getSelectedText();
                    if (StringUtils.isNullOrEmpty(selectedSQLText)) {
                        return;
                    }
                    //判断是否有connection对象
                    if (null == currentSelectedConnection) {
                        currentSelectedConnection = currentSelectedConnectionInfoEntity.getNewConnection();
                    }
                    PreparedStatement statement = null;
                    ResultSet rs = null;
                    String lowerSelectedSQLText = selectedSQLText.trim().toLowerCase();
                    if (lowerSelectedSQLText.startsWith("select")) {
                        //查询
                        statement = currentSelectedConnection.prepareStatement(selectedSQLText);
                        rs = statement.executeQuery();
                        if (rs != null) {
                            DefaultTableModel tableModel = readResultSet(rs);
                            if (null != tableModel) {
                                sqlEditPanel.getDataGrid().setModel(tableModel);
                                sqlEditPanel.getDataGrid().paintRow();
                                sqlEditPanel.getDataGrid().fitTableColumns();
                            } else {
                                //没有数据处理
                                sqlEditPanel.setBottomTextPanel("没有数据");
                            }

                        }
                    } else if (lowerSelectedSQLText.startsWith("delete") ||
                            lowerSelectedSQLText.startsWith("update") ||
                            lowerSelectedSQLText.startsWith("insert")) {
                        //DML
                        statement = currentSelectedConnection.prepareStatement(selectedSQLText);
                        int count = statement.executeUpdate();

                    } else if (lowerSelectedSQLText.startsWith("create") ||
                            lowerSelectedSQLText.startsWith("drop") ||
                            lowerSelectedSQLText.startsWith("alter")) {
                        //DDL
                        statement = currentSelectedConnection.prepareStatement(selectedSQLText);
                        statement.execute();

                    } else if (lowerSelectedSQLText.startsWith("call")) {
                        //调用存储过程 prepareCall("{CALL xxx()}")
                        statement = currentSelectedConnection.prepareCall("{" + selectedSQLText + "}");
                        statement.execute();
                        rs = statement.getResultSet();
                        if (rs != null) {
                            DefaultTableModel tableModel = readResultSet(rs);
                            if (null != tableModel) {
                                sqlEditPanel.getDataGrid().setModel(tableModel);
                                sqlEditPanel.getDataGrid().paintRow();
                                sqlEditPanel.getDataGrid().fitTableColumns();
                            } else {
                                //没有数据处理
                                sqlEditPanel.setBottomTextPanel("没有数据");
                            }
                        }
                    } else {
                        //其他sql
                        statement = currentSelectedConnection.prepareStatement(selectedSQLText);
                        statement.execute();
                    }
                    if (rs != null) {
                        rs.close();
                    }
                    if (statement != null) {
                        statement.close();
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        });

        //连接下拉框选择事件
        connectionCombobox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent event) {
                //选中事件
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    intCombobox(databaseCombobox);
                    if (connectionCombobox.getSelectedIndex() == 0) {

                    } else {
                        LeftPanelTreeNode connectionInfoNode = (LeftPanelTreeNode) connectionCombobox.getSelectedItem();
                        List<LeftPanelTreeNode> databaseItemNodes = LeftPanel.getInstance().getChildNodesForNode(connectionInfoNode);
                        for (LeftPanelTreeNode databaseNode : databaseItemNodes) {
                            databaseCombobox.addItem(databaseNode);
                        }
                        //当前选中连接信息节点
                        if (currentSelectedConnectionInfoNode != connectionInfoNode) {
                            currentSelectedConnectionInfoNode = connectionInfoNode;
                            currentSelectedConnectionInfoEntity = (ConnectionInfoEntity) connectionInfoNode.getUserObject();
                        }
                    }
                }
            }
        });
    }

    public void intCombobox(JComboBox comboBox) {
        comboBox.removeAllItems();
        comboBox.addItem(baseTextResource.getPleseSelect());
    }

    public List<LeftPanelTreeNode> getAllLevel1ConnectionInfoNodes() {
        return allLevel1ConnectionInfoNodes;
    }

    public void setAllLevel1ConnectionInfoNodes(List<LeftPanelTreeNode> allLevel1ConnectionInfoNodes) {
        this.allLevel1ConnectionInfoNodes = allLevel1ConnectionInfoNodes;
        if (allLevel1ConnectionInfoNodes != null) {
            this.intCombobox(this.connectionCombobox);
            this.intCombobox(this.databaseCombobox);
            for (LeftPanelTreeNode connectionInfoNode : allLevel1ConnectionInfoNodes) {
                this.connectionCombobox.addItem(connectionInfoNode);
            }
            this.connectionCombobox.setSelectedIndex(0);
        }
    }

    public JComboBox getConnectionCombobox() {
        return connectionCombobox;
    }

    public void setConnectionCombobox(JComboBox connectionCombobox) {
        this.connectionCombobox = connectionCombobox;
    }

    public JComboBox getDatabaseCombobox() {
        return databaseCombobox;
    }

    public void setDatabaseCombobox(JComboBox databaseCombobox) {
        this.databaseCombobox = databaseCombobox;
    }

    public SQLEditPanel getSqlEditPanel() {
        return sqlEditPanel;
    }

    public void setSqlEditPanel(SQLEditPanel sqlEditPanel) {
        this.sqlEditPanel = sqlEditPanel;
    }
}
